from ctypes import *
import ctypes
import numpy as np
import pyvista as pv
from pyvistaqt import QtInteractor, MainWindow
dll = cdll.LoadLibrary("./dll/PTTLibrary.dll")

def read_ptt(ptt_path):
    Width = ctypes.c_int(0)  # Image Width
    Length =ctypes.c_int(0)    # Image Length
    pixelSize =ctypes.c_int(0) # Bytes of Pixel (Image)     3:BGR(Blue Green Red), 2:BR(Blue Red)
    ResolutionX =ctypes.c_float(0)# Pixel Resoultion X(um)
    ResolutionY =ctypes.c_float(0)  # Pixel Resoultion Y(um)

    ROIStartX =ctypes.c_float(0) #ROI StartX(Pixel)
    ROIStartY  =ctypes.c_float(0)#ROI StartY (Pixel)
    ROIWidth  =ctypes.c_float(0)   #ROI Width (pixel)
    ROILength =ctypes.c_float(0)  #ROI Lengh (PIXEL)

    ptt = dll.ReadPTTBufferSizeExtend(ptt_path,
                                      ctypes.byref(Width),
                                      ctypes.byref(Length),
                                      ctypes.byref(pixelSize),
                                      ctypes.byref(ResolutionX),
                                      ctypes.byref(ResolutionY),
                                      ctypes.byref(ROIStartX),
                                      ctypes.byref(ROIStartY),
                                      ctypes.byref(ROIWidth),
                                      ctypes.byref(ROILength))
    heightMap = (c_float * (Width.value * Length.value))()
    IamgeMap = (c_ubyte*(Width.value*Length.value*pixelSize.value))()
    ptt2 = dll.ReadPTTBuffer(ptt_path, heightMap, IamgeMap)
    height_img = np.ctypeslib.as_array(heightMap)
    img_map = np.ctypeslib.as_array(IamgeMap)
    # grayImage = height_img.reshape(Length.value, Width.value)
    img = img_map.reshape(Length.value, Width.value, pixelSize.value)
    img = np.flip(img,axis=0)
    grid = pv.ImageData(dimensions=(Width.value, Length.value, 1),spacing=(int(ResolutionX.value),int(ResolutionY.value),1.0))
    grid.point_data.set_array(heightMap,'a')
    # grid.spacing
    # terrain = grid.warp_by_scalar(factor=1 / 20)
    # terrain.texture_map_to_plane(use_bounds=True, inplace=True)
    texture = pv.Texture(img)
    # terrain.plot(texture=texture)
    return grid,texture
    # grid.point_data[""]




if __name__=='__main__':
    ptt_path = r'D:\WJY\PTT_1\1@4 (2).ptt'
    read_ptt(ptt_path)
